import Taro, { useRouter } from '@tarojs/taro'
import React, { useEffect, useState, useMemo } from 'react'
import { View, ScrollView } from '@tarojs/components'
import ServicePackCard from '@SUBPACKAGES/servicePack/component/ServicePackCard'
import { TemplateITF } from '@INTERFACES/ServicePackITF'
import ModuleTitle from '@COMPONENTS/ModuleTitle'
import api from '@API'
import { getPlatform } from '@UTILS/common'
import { useSelector } from 'react-redux'
import { RootStateITF } from '@REDUXITF/index'
import './RecommendService.scss'

const { isWeb } = getPlatform()

const RecommendService: React.FC = () => {
  const language = 'zh'
  const router = useRouter()
  const userId = useSelector<RootStateITF, string | undefined>(state => state.profile.user?.p8Id)
  const { appkey } = useMemo(() => router.params, [router])
  const [dataList, setDataList] = useState([])

  const fetchData = async (cId: string) => {
    try {
      const data = await api.getTemplatesByClient({ cId })
      const { Templates } = data || {}
      setDataList(Templates)
    } catch (error) {
      Taro.showToast({
        title: error.message || error,
        icon: 'none'
      })
    }
  }

  useEffect(() => {
    if (!isWeb || !userId) return
    appkey && fetchData(appkey)
  }, [appkey, userId])

  if (!isWeb || !dataList?.length) return null

  return (
    <View className="rs-container">
      <View />
      <ModuleTitle title="推荐服务" showMore={false} />
      <ScrollView scrollX scrollWithAnimation>
        <View className="rs-content">
          {Array.isArray(dataList) && dataList.map((item: TemplateITF) => (
            <ServicePackCard
              data={item}
              key={item.p8Id}
              language={language}
              needCheckType={false}
            />
          ))}
        </View>
      </ScrollView>
    </View>
  )
}

export default RecommendService
